package com.admin.service.impl;

import com.admin.dao.UserMapper;
import com.admin.entity.Role;
import com.admin.dao.RoleMapper;
import com.admin.entity.User;
import com.admin.service.RoleService;
import com.admin.vo.query.RoleQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author szy
 * @since 2023-02-21
 */
@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    private UserMapper userMapper;

    /*根据用户查询角色列表*/
    @Override
    public IPage<Role> findRoleListByUserId(IPage<Role> page, RoleQueryVo roleQueryVo) {
        //构造条件构造器
        QueryWrapper<Role> queryWrapper = new QueryWrapper<Role>();
        //角色名称
        queryWrapper.like(!ObjectUtils.isEmpty(roleQueryVo.getRoleName()),
                "role_name",roleQueryVo.getRoleName());
        //排序
        queryWrapper.orderByAsc("id");

        return baseMapper.selectPage(page,queryWrapper);
    }

    /*删除角色*/
    @Override
    public boolean deleteRoleById(Long id) {
        /*删除角色-权限*/
        baseMapper.deleteRolePermissionByRoleId(id);
        /*删除角色*/
        return  baseMapper.deleteById(id)>0;
    }

    @Override
    public boolean hashRoleCount(Long id) {
        return baseMapper.getRoleCountByRoleId(id)>0;
    }

    /*保存角色-权限信息*/
    @Override
    public boolean saveRolePermission(Long roleId, List<Long> permissionIds) {
        baseMapper.deleteRolePermissionByRoleId(roleId);
        return baseMapper.saveRolePermission(roleId,permissionIds)>0;
    }

    /*根据用户id查询该用户拥有的角色信息*/
    @Override
    public List<Long> findRoleIdByUserId(Long userId) {
        return baseMapper.findRoleIdByUserId(userId);
    }

}
